package com.gy;

import android.content.Context;
import android.os.Build;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by gy on 17-7-19.
 */

public class TempReplace {
    public final static String BIN = "run";
    public final static String USB_XML = "usb_device_manager.xml";
    public final static String USB_XML_2 = "usb_device_manager2.xml";
    public final static String toReplace = "/system/bin/vold";

    static {
        System.loadLibrary("replace");
    }

    /**
     * 调用此方法可将assets/abi/run 暂时替换至toreplace文件。重启后失效
     * 可执行文件run执行三步
     *  1.将/data/data/'packagename'/cache/USB_XML 文件复制到/data/system/users/0/
     *  2.执行 pm hide com.syu.dvr
     *  3.执行 reboot
     * @param context
     */
    public static void main(Context context) {
        String exeFilePath = context.getCacheDir().getAbsolutePath() + "/" + BIN;
        String eabiDir = "armeabi-v7a";
        String abi = Build.CPU_ABI;
        if (abi.startsWith("armeabi-v7a")) {
            eabiDir = "armeabi-v7a";
        } else if (abi.startsWith("x86")) {
            eabiDir = "x86";
        }
        copyAsset(context, eabiDir + File.separator + BIN, exeFilePath);
        if(Build.MODEL.toLowerCase().contains("k1s")){
            copyAsset(context, USB_XML_2, context.getCacheDir().getAbsolutePath() + "/" + USB_XML);
        }else {
            copyAsset(context, USB_XML, context.getCacheDir().getAbsolutePath() + "/" + USB_XML);
        }
        new TempReplace().action(new String[]{exeFilePath, toReplace});
    }

    public native int action(String[] args);

    public static void copyAsset(Context context, String assetPath, String toFilePath) {
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        try {
            inputStream = context.getAssets().open(assetPath);
            fileOutputStream = new FileOutputStream(toFilePath);
            byte[] buf = new byte[4096];

            int len;
            while ((len = inputStream.read(buf)) > 0) {
                fileOutputStream.write(buf, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
